#include <iostream>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <vector>
#include <iomanip>

// 打开串口并配置参数
int openAndConfigureSerialPort(const std::string& portName) {
    int fd = open(portName.c_str(), O_RDWR | O_NOCTTY);
    if (fd < 0) {
        std::cerr << "无法打开串口: " << portName << std::endl;
        return -1;
    }

    struct termios options;
    tcgetattr(fd, &options);
    cfsetispeed(&options, B9600);
    cfsetospeed(&options, B9600);
    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cflag |= (CLOCAL | CREAD);
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    options.c_oflag &= ~OPOST;
    tcsetattr(fd, TCSANOW, &options);
    tcflush(fd, TCIOFLUSH);
    return fd;
}

int main() {
    std::string portName = "/dev/ttyUSB0"; // 根据实际串口号修改
    int fd = openAndConfigureSerialPort(portName);
    if (fd < 0) {
        return 1;
    }

    char buffer[256];
    std::vector<unsigned char> frameBuffer;
    bool inFrame = false;

    std::cout << "开始接收并打印串口数据帧..." << std::endl;
    while (true) {
        int bytesRead = read(fd, buffer, sizeof(buffer));
        if (bytesRead > 0) {
            for (int i = 0; i < bytesRead; ++i) {
                unsigned char byte = static_cast<unsigned char>(buffer[i]);
                if (!inFrame) {
                    if (byte == 0x6A) {
                        frameBuffer.clear();
                        frameBuffer.push_back(byte);
                        inFrame = true;
                    }
                } else {
                    frameBuffer.push_back(byte);
                    if (frameBuffer.size() == 9) {
                        std::cout << "完整帧数据（十六进制）: ";
                        for (unsigned char b : frameBuffer) {
                            std::cout << std::hex << std::setw(2) << std::setfill('0') 
                                      << static_cast<int>(b) << " ";
                        }
                        std::cout << std::endl;
                        frameBuffer.clear();
                        inFrame = false;
                    }
                }
            }
        } else if (bytesRead < 0) {
            std::cerr << "读取串口数据失败" << std::endl;
        }
    }

    close(fd);
    return 0;
}